package com.songlanyun.modules.marketing.groupbuy.controller.admin;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.MarketingConstant;
import com.songlanyun.common.enums.PrivateMessageConstant;
import com.songlanyun.common.enums.SysConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.exception.MarketingException;
import com.songlanyun.modules.marketing.groupbuy.model.dto.GroupBuyActivityDTO;
import com.songlanyun.modules.message.entity.PrivateMessage;
import com.songlanyun.modules.message.model.ActivityMessage;
import com.songlanyun.modules.message.model.to.MessageTO;
import com.songlanyun.modules.message.model.to.PrivateMessageTO;
import com.songlanyun.modules.message.service.SendPrivateMessageMsgService;
import com.songlanyun.modules.rabbitmq.MqConstant;
import com.songlanyun.modules.rabbitmq.service.SendMsgService;
import com.songlanyun.modules.user.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyActivity;
import com.songlanyun.modules.marketing.groupbuy.service.GroupBuyActivityService;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;

import javax.annotation.Resource;


/**
 * 拼团活动
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-11-27 14:03:39
 */
@RestController
@RequestMapping("admin/groupbuy/activity")
public class GroupBuyActivityAdminController extends AbstractController {
    @Autowired
    private GroupBuyActivityService groupBuyActivityService;

    @Resource
    private SendPrivateMessageMsgService sendPrivateMessageMsgService;


    /**
     * 列表
     */
    @GetMapping("/list")
//    @RequiresPermissions("groupbuy:groupBuyActivity:list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("shop_id", getShopId(true));
        PageUtils page = groupBuyActivityService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
//    @RequiresPermissions("groupbuy:groupBuyActivity:info")
    public R info(@PathVariable("id") Long id) {
        GroupBuyActivity groupBuyActivity = groupBuyActivityService.getById(id);

        return R.ok().put("data", groupBuyActivity);
    }

    /**
     * 新建拼团
     */
    @SysLog("新建拼团")
    @PostMapping("/save")
//    @RequiresPermissions("groupbuy:groupBuyActivity:save")
    public R save(@RequestBody GroupBuyActivityDTO dto) {
        ValidatorUtils.validateEntity(dto);
        verifyName(dto.getName());//检验名称
        dto.setShopId(getShopId(true));
        //保存
        GroupBuyActivity groupBuyActivity = groupBuyActivityService.saveGroupBuy(dto);

        //发送站内消息    给商家下的所有会员
        sendPrivateMessageMsgService.send(new MessageTO(PrivateMessageConstant.MessageType.ACTIVITY_MESSAGE,
                PrivateMessageConstant.ModelType.GROUP_BUY, groupBuyActivity.getId()));

        return R.ok();
    }

    /**
     * 修改拼团
     */
    @SysLog("修改拼团")
    @PutMapping("/update")
//    @RequiresPermissions("groupbuy:groupBuyActivity:update")
    public R update(@RequestBody GroupBuyActivityDTO dto) {
        ValidatorUtils.validateEntity(dto);
        verifyActiveState(dto.getId(), 0);//检验状态
        GroupBuyActivity activiey = groupBuyActivityService.getById(dto.getId(), true);
        if (!activiey.getName().equals(dto.getName())) {
            verifyName(dto.getName());//检验名称
        }

        groupBuyActivityService.updateGroupBuy(dto);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除拼团")
    @DeleteMapping("/delete/{id}")
//    @RequiresPermissions("groupbuy:groupBuyActivity:delete")
    public R delete(@PathVariable("id") Long id) {
        verifyActiveState(id, 1);//检验状态

        groupBuyActivityService.delById(id);

        return R.ok();
    }


    /**
     * 校验活动状态
     *
     * @param id
     */
    private void verifyActiveState(Long id, Integer operationType) {
        GroupBuyActivity groupBuyActivity = groupBuyActivityService.getById(id, true);
        //拼团活动正在进行中，不能修改
        if (MarketingConstant.ActiveState.UNDERWAY.equals(groupBuyActivity.getActiveState())) {
            throw new RRException(MarketingException.GROUP_BUY_ACTIVITY_UNDERWAY);
        }
        if (operationType == 0) {
            //拼团活动结束，不能修改
            if (MarketingConstant.ActiveState.FINISHED.equals(groupBuyActivity.getActiveState())) {
                throw new RRException(MarketingException.GROUP_BUY_ACTIVITY_FINISH);
            }
        }


    }

    /**
     * 检验当前店铺的拼团活动名称是否重复
     *
     * @param name
     */
    private void verifyName(String name) {
        int count = groupBuyActivityService.count(
                new LambdaQueryWrapper<GroupBuyActivity>()
                        .eq(GroupBuyActivity::getShopId, getShopId(true))
                        .eq(GroupBuyActivity::getName, name)
        );
        if (count > 0) {
            throw new RRException(MarketingException.GROUP_BUY_ACTIVITY_NAME_REPETITION);
        }
    }

}
